﻿using System;
using System.Collections;
using System.Runtime.CompilerServices;
using jQueryApi;

namespace StorytellingScript
{
    [GlobalMethods]
    public static class Vampiro
    {
        public static void ConfigurarAtributosPreferenciais()
        {
            jQuery.Select("#Cla").Plugin<StorytellingPlugin>().Bind("autocompleteselect",
               new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
               {
                   jQueryAjaxOptions options = new jQueryAjaxOptions();
                   options.Url = "/Cla/CarregarHeranca";
                   options.Type = "POST";
                   options.DataType = "json";
                   options.Data = new Dictionary("id", Script.Literal("{0}.item.value", ui));
                   options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                   {
                       jQueryObject opcaoUm = jQuery.Select("#opcaoUm");
                       jQueryObject opcaoDois = jQuery.Select("#opcaoDois");

                       switch (Int32.Parse(data.ToString()))
                       {
                            case 0:
                                opcaoUm.Html("Destreza");
                                opcaoDois.Html("Manipulação");
                                break;
                            case 1:
                                opcaoUm.Html("Autocontrole");
                                opcaoDois.Html("Vigor");
                                break;
                            case 2:
                                opcaoUm.Html("Inteligência");
                                opcaoDois.Html("Raciocínio");
                                break;
                            case 3:
                                opcaoUm.Html("Autocontrole");
                                opcaoDois.Html("Força");
                                break;
                            case 4:
                                opcaoUm.Html("Presença");
                                opcaoDois.Html("Perseverança");
                                break;
                       }
                   });

                   jQuery.Ajax(options);
                   return false;
               }));
        }

        public static void ConfigurarEvolucaoVampiro()
        {
            jQueryObject comp = jQuery.Select("#LabelEvolucaoPenalidadeVontade");
            comp.Bind("click", new jQueryEventHandler(delegate(jQueryEvent e)
            {
                comp.FadeOut();

                jQueryObject label = comp.Find("label");

                jQuery.Select(string.Format("#evolucao tr[class=evolucao_4_1]:last")).Find("td:nth-child(5)").Html("");

                int custo = 8;

                jQuery.Select("#evolucao tbody").Append(string.Format(Template.EvolucaoGenerico, "4", "1", label.GetHtml(), "", "", custo));

                jQueryObject gasto = jQuery.Select("#experienciaGasto");
                gasto.Html((Int32.Parse(gasto.GetHtml()) + custo).ToString());

                Evolucao.Calcular();

                jQueryObject inputEvolucao = jQuery.Select("#inputEvolucao");

                jQueryObject divEvolucao = inputEvolucao.Find("#divEvolucao_4_1");

                if (divEvolucao.Length == 0)
                {
                    inputEvolucao.Append(string.Format(Template.EvolucaoIncremento, "4", "1"));
                }
                else
                {
                    jQueryObject incrementos = divEvolucao.Find("input[name=Incrementos]");
                    incrementos.Value((Int32.Parse(incrementos.GetValue()) + 1).ToString());
                }

                comp.FadeIn();
            }));
        }

        public static void ConfigurarAutocompleteEvolucaoVampiro()
        {
            string url = "";
            int tipo = Int32.Parse(jQuery.Select("#selecaoEvolucao").GetValue());

            switch (tipo)
            {
                case 5:
                    url = "/Devocao/Autocompletar";
                    break;
                case 6:
                    url = "/Disciplina/Autocompletar";
                    break;
                case 7:
                    url = "/Ritual/Autocompletar";
                    break;
            }

            jQueryObject autoEvolucao = jQuery.Select("#autoEvolucao");
            autoEvolucao.Unbind("autocomplete");

            autoEvolucao.Plugin<StorytellingPlugin>().Autocomplete(new Dictionary(
                "source", new Action<object, Action<object>>(delegate(object request, Action<object> response)
                {
                    jQueryAjaxOptions options = new jQueryAjaxOptions();
                    options.Url = url;
                    options.Type = "POST";
                    options.DataType = "json";
                    options.Data = new Dictionary("nome", Script.Literal("{0}.term", request));
                    options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                    {
                        response(jQuery.Map(data, new ObjectMapCallback(delegate(object item, string key)
                        {
                            return new Dictionary("label", Script.Literal("{0}.Nome", item), "value", Script.Literal("{0}.Id", item));
                        })));
                    });

                    jQuery.Ajax(options);
                }),
                "focus", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                {
                    autoEvolucao.Value(Script.Literal("{0}.item.label", ui).ToString());
                    return false;
                }),
                "select", new Func<jQueryEvent, object, bool>(delegate(jQueryEvent e, object ui)
                {
                    jQueryAjaxOptions options = new jQueryAjaxOptions();

                    jQueryObject inputEvolucao = jQuery.Select("#inputEvolucao");

                    int quant = jQuery.Select(string.Format("#evolucao .evolucao_{0}_{1}", tipo, Script.Literal("{0}.item.value", ui))).Size();

                    jQueryObject gasto = jQuery.Select("#experienciaGasto");

                    switch (tipo)
                    {
                        case 5:
                            options.Url = "/Devocao/CustoExperiencia";
                            options.Type = "POST";
                            options.DataType = "json";
                            options.Data = new Dictionary("id", Script.Literal("{0}.item.value", ui));
                            options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                            {
                                jQueryObject vampiroDevocao = jQuery.Select(string.Format(".DevocoesId[value='{0}']", Script.Literal("{0}.item.value", ui)));

                                if (vampiroDevocao.Length == 0 && quant == 0)
                                {
                                    jQuery.Select("#evolucao tbody").Append(string.Format(Template.EvolucaoGenerico, "5", Script.Literal("{0}.item.value", ui),
                                        Script.Literal("{0}.item.label", ui), "Devoção", "", data));

                                    inputEvolucao.Append(string.Format(Template.EvolucaoIncremento, "5", Script.Literal("{0}.item.value", ui)));

                                    gasto.Html((Int32.Parse(gasto.GetHtml()) + (int)data).ToString());

                                    Evolucao.Calcular();
                                }
                            });
                            break;
                        case 6:
                            options.Url = "/Cla/DisciplinaFamiliar";
                            options.Type = "POST";
                            options.DataType = "json";
                            options.Data = new Dictionary(
                                "id", Int32.Parse(jQuery.Select("input[name=ClaValor]").GetValue()),
                                "idDisciplina", Script.Literal("{0}.item.value", ui));
                            options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                            {
                                int nivel = 0;
                                int agrupamento = 0;
                                int extra = 0;

                                jQuery.Select(string.Format("#evolucao tr[class=evolucao_6_{0}]:last", Script.Literal("{0}.item.value", ui))).Find("td:nth-child(5)").Html("");

                                jQueryObject vampiroDisciplina = jQuery.Select(string.Format(".DisciplinasId[value='{0}']", Script.Literal("{0}.item.value", ui)));

                                jQueryObject tbody = jQuery.Select("#evolucao tbody");

                                if (vampiroDisciplina.Length != 0)
                                {
                                    nivel = Int32.Parse(vampiroDisciplina.Parent().Parent().Find("input[name=VampiroDisciplinaNiveis]").GetValue()); 
                                    agrupamento = Int32.Parse(vampiroDisciplina.GetAttribute("agrupamento"));

                                    if (agrupamento > 0)
                                    {
                                        jQuery.Each(jQuery.Select(string.Format(".DisciplinasId[agrupamento='{0}']", agrupamento)), 
                                            new ObjectIterationCallback(delegate(string name, object value)
                                        {
                                            extra += Int32.Parse(jQuery.FromObject(value).Parent().Parent().Find("input[name=VampiroDisciplinaNiveis]").GetValue());  
                                        }));
                                        extra -= nivel;
                                        extra += tbody.Find(string.Format("tr[agrupamento='{0}']", agrupamento)).Size();
                                    }
                                }

                                int custo = (nivel + extra + quant + 1) * (((bool)data) ? 5 : 7);

                                tbody.Append(string.Format(Template.EvolucaoDisciplina, Script.Literal("{0}.item.value", ui),
                                    agrupamento, Script.Literal("{0}.item.label", ui), Global.Pontos(nivel + quant + 1), custo));

                                jQueryObject divEvolucao = inputEvolucao.Find(string.Format("#divEvolucao_6_{0}", Script.Literal("{0}.item.value", ui)));

                                if (divEvolucao.Length == 0)
                                {
                                    inputEvolucao.Append(string.Format(Template.EvolucaoIncremento, "6", Script.Literal("{0}.item.value", ui)));
                                }
                                else
                                {
                                    jQueryObject incrementos = divEvolucao.Find("input[name=Incrementos]");
                                    incrementos.Value((Int32.Parse(incrementos.GetValue()) + 1).ToString());
                                }

                                gasto.Html((Int32.Parse(gasto.GetHtml()) + custo).ToString());

                                Evolucao.Calcular();
                                autoEvolucao.Plugin<StorytellingPlugin>().Autocomplete("search");
                            });
                            break;
                        case 7:
                            options.Url = "/Ritual/CustoExperiencia";
                            options.Type = "POST";
                            options.DataType = "json";
                            options.Data = new Dictionary(
                                "id", Script.Literal("{0}.item.value", ui),
                                "idVampiro", Int32.Parse(jQuery.Select("input[name=Id]").GetValue()));
                            options.Success = new AjaxRequestCallback(delegate(object data, string textStatus, jQueryXmlHttpRequest httpRequest)
                            {
                                jQueryObject vampiroRitual = jQuery.Select(string.Format(".RituaisId[value='{0}']", Script.Literal("{0}.item.value", ui)));

                                if (vampiroRitual.Length == 0 && quant == 0)
                                {
                                    int nivel = (int)Script.Literal("{0}.Nivel", data);
                                    if (nivel > 0)
                                    {
                                        int custo = 0;
                                        long disciplinaId = (long) Script.Literal("{0}.DisciplinaId", data);

                                        jQueryObject tbody = jQuery.Select("#evolucao tbody");

                                        if (!((bool)Script.Literal("{0}.IsGratis", data)) || tbody.Find(string.Format("tr[categoriaRitual='{0}_{1}']",
                                            disciplinaId, nivel)).Size() > 0)
                                        {
                                            custo = nivel * 2;
                                        }

                                        tbody.Append(string.Format(Template.EvolucaoRitual, Script.Literal("{0}.item.value", ui),
                                            disciplinaId, nivel, Script.Literal("{0}.item.label", ui), Global.Pontos(nivel), custo));

                                        inputEvolucao.Append(string.Format(Template.EvolucaoIncremento, "7", Script.Literal("{0}.item.value", ui)));

                                        gasto.Html((Int32.Parse(gasto.GetHtml()) + custo).ToString());

                                        Evolucao.Calcular(); 
                                    }
                                } 
                            });
                            break;
                    }

                    jQuery.Ajax(options);
                    return false;
                })
                ));
        }
    }
}
